package org.csu.demo.db.Controller;

import jakarta.servlet.http.HttpSession;
import org.csu.demo.db.domain.Students;
import org.csu.demo.db.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class studentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("/students")
    public String getAllStudents(Model model, HttpSession session) {
        if (session.getAttribute("currentUser") == null) {
            return "redirect:/login";
        }
        List<Students> students = studentService.getAllStudents();
        model.addAttribute("students", students);
        return "students";
    }

    @GetMapping("/students/{id}")
    public String getStudentById(@PathVariable String id, Model model, HttpSession session) {
        if (session.getAttribute("currentUser") == null) {
            return "redirect:/login";
        }
        Students student = studentService.getStudentById(id);
        model.addAttribute("student", student);
        return "student";
    }

    @PostMapping("/students")
    public String addStudent(@ModelAttribute Students student, RedirectAttributes redirectAttributes) {
        studentService.addStudent(student);
        redirectAttributes.addFlashAttribute("message", "学生添加成功");
        return "redirect:/students";
    }

    @PutMapping("/students/{id}")
    public String updateStudent(@PathVariable String id, @ModelAttribute Students student, Model model, RedirectAttributes redirectAttributes) {
        System.out.println("Received student update - ID: " + id + ", Name: " + student.getName());
        student.setId(id);
        studentService.updateStudent(student);
        model.addAttribute("student", student);
        redirectAttributes.addFlashAttribute("message", "学生信息修改成功");
        return "redirect:/students/" + id;
    }

    @DeleteMapping("/students/{id}")
    public String deleteStudent(@PathVariable String id, RedirectAttributes redirectAttributes) {
        studentService.deleteStudent(id);
        redirectAttributes.addFlashAttribute("message", "学生删除成功");
        return "redirect:/students";
    }
}